import sys
import time
import swmixer
import numpy
import matplotlib
fs=11025
swmixer.init(samplerate=fs, chunksize=1024, stereo=False, microphone=True)
# snd = swmixer.Sound("test1.wav")
# snd.play(loops=-1)


# 82.4 E - open 6th string
# 110.0 A - open 5th string
# 146.8 D - open 4th string
# 196.0 G - open 3rd string
# 246.9 B - open 2nd string
# 329.6 E - open 1st string 

micdata = []
frame = 0
#http://entertainment.howstuffworks.com/guitar3.htm
#http://www.vaughns-1-pagers.com/music/musical-note-frequencies.htm
matplotlib.pyplot.figure();
foo=raw_input('Adjust plot and hit enter')
for ll in range(10):
    print('Get ready to hit string ' + str(ll) + ' of 10')
    time.sleep(1)
    
    print('NOW')
    time.sleep(.5)
    for frame in range(31):    
        swmixer.tick()        
        if frame == 0:
            dropFrame=swmixer.get_microphone()
        if frame < 30:
            micdata = numpy.append(micdata, swmixer.get_microphone())
        elif frame == 30:
            print 'Snapped Frame'
            micdata = numpy.append(micdata, swmixer.get_microphone())
            micsnd = swmixer.Sound(data=micdata)        
            micsnd.play()
            sp = numpy.fft.fft(a=micdata,n=numpy.power(2,16))
            
            freq = numpy.fft.fftfreq(n=sp.shape[-1],d=(1/float(fs)))
            goodFreqIdx=((freq>50) & (freq<2000))
            goodFreq=freq[goodFreqIdx]
            
            sp=20*numpy.log10(numpy.abs(sp[goodFreqIdx]))
            matplotlib.pyplot.hold(False)
            matplotlib.pyplot.plot(goodFreq,sp)
            matplotlib.pyplot.xlabel('Frequency (Hz)')
            matplotlib.pyplot.ylabel('Magnitude (dB)')
#string 5 110 A           
#            searchFreqIdx=((goodFreq>90) & (goodFreq<140))

#string 4 146.8 D
#            searchFreqIdx=((goodFreq>120) & (goodFreq<170))
            
#string 3 196.0 G 
#            searchFreqIdx=((goodFreq>170) & (goodFreq<220))

#string 2 246.9 B
#            searchFreqIdx=((goodFreq>220) & (goodFreq<270))

#string 1 329.6 E
            searchFreqIdx=((goodFreq>300) & (goodFreq<360))
            
            searchFreq=goodFreq[searchFreqIdx]
            maxFreqIdx=numpy.argmax(sp[searchFreqIdx])
            matplotlib.pyplot.title('Max freq is ' + str(searchFreq[maxFreqIdx])[0:6] +'Hz')
                
            micdata = []
      
            
    print('Adjust String')
    time.sleep(2)
print('Finished')
    
swmixer.quit()
# snd=[]